package com.cz;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;

/*
 * @Description:
 * @Author: chenzhen
 * @Date: 2023/5/19 15:03
 */
public class SendMessageAsync {
    public static void main(String[] args) {
        DefaultMQProducer producer = null;
        try {
            CountDownLatch latch = new CountDownLatch(1);
            producer = new DefaultMQProducer("test");
            producer.setNamesrvAddr("172.16.1.210:9876");
            producer.start();

            String topic = "czbabl_test";
            String messageBody = "Hello, RocketMQ!";

            // 创建消息对象
            Message message = new Message(topic, messageBody.getBytes());

            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    latch.countDown();
                    System.out.println("Message sent successfully. Result: " + sendResult);
                }

                @Override
                public void onException(Throwable e) {
                    latch.countDown();
                    e.printStackTrace();
                }
            });
            latch.await();
        }catch (Exception e){
            System.out.println("Failed to send message.");
            e.printStackTrace();
        } finally {
           producer.shutdown();
        }
    }
}
